package com.springboot.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.springboot.eduservice.entity.Chapter.ChapterVo;
import com.springboot.eduservice.entity.Chapter.VideoVo;
import com.springboot.eduservice.entity.EduChapter;
import com.springboot.eduservice.entity.EduVideo;
import com.springboot.eduservice.mapper.EduChapterMapper;
import com.springboot.eduservice.service.EduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springboot.servicebase.exceptionhandler.GuliException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-05-12
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {
    @Autowired
    private EduVideoServiceImpl eduVideoService;
    public List<ChapterVo> getChapterbyid(String courseid){
        //用于最终封装课程章节信息
        List<ChapterVo> finallchapter = new ArrayList<>();
        //查询章节信息
        QueryWrapper<EduChapter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id",courseid);
        List<EduChapter> eduChapters = baseMapper.selectList(queryWrapper);
       //查询小节信息
        QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseid);
        List<EduVideo> videoList = eduVideoService.list(wrapper);

        for (int i = 0; i < eduChapters.size(); i++) {
            EduChapter chapter = eduChapters.get(i);
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(chapter,chapterVo);
            finallchapter.add(chapterVo);
            //封装小节信息
            List<VideoVo> finallvidevo = new ArrayList<>();
            for (int n = 0; n < videoList.size(); n++) {
                EduVideo video = videoList.get(n);
                if (chapter.getId().equals(video.getChapterId())){
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(video,videoVo);
                    finallvidevo.add(videoVo);
                }
            }
            chapterVo.setChildren(finallvidevo);

        }

        return finallchapter;
    }

    //删除章节，如果存在小节不能删除
    public void deleteVideo(String chapterid){
        QueryWrapper<EduVideo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("chapter_id",chapterid);
        List<EduVideo> list = eduVideoService.list(queryWrapper);
        if (list == null){
            throw new GuliException(20001,"删除失败，存在小节不能删除");
        }else {
            baseMapper.deleteById(chapterid);

        }

    }
    public int deleteChapterById(String courseId){
        int deleteChapterById = baseMapper.deleteChapterById(courseId);
        return deleteChapterById;
    }

}
